package com.jalarbee.web.jsf.converter;

import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.ConverterException;

import com.jalarbee.stock.category.business.Category;
import com.jalarbee.stock.category.dao.CategoryDao;
import org.springframework.web.jsf.FacesContextUtils;

public class CategoryConverter implements Converter {

    @Override
    public Object getAsObject(FacesContext context, UIComponent component, String string) {
        try {
            if (string == null) {
                return null;
            }
            CategoryDao categoryDao = (CategoryDao)FacesContextUtils.getWebApplicationContext(context).getBean("categoryDao");
            return categoryDao.getCategorByName(string);
        } catch (Exception e) {
            throw new ConverterException(e);
        }

    }

    @Override
    public String getAsString(FacesContext context, UIComponent component, Object object) {
        try {
            return String.valueOf(((Category) object).getName());
        } catch (Exception e) {
            throw new ConverterException(e);
        }
    }

}
